package ext.tianma.bom.service;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ptc.core.meta.type.mgmt.server.impl.WTTypeDefinition;

import ext.com.iba.IBAUtil;
import ext.tianma.bom.util.EnumerationUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.QueryUtil;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.httpgw.URLFactory;
import wt.iba.definition.FloatDefinition;
import wt.iba.value.FloatValue;
import wt.log4j.LogR;
import wt.method.MethodContext;
import wt.part.WTPart;
import wt.pom.WTConnection;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.OneOffVersionIdentifier;
import wt.vc.OneOffVersionInfo;
import wt.vc.VersionControlHelper;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

/**
 * 成品物料接口
 * 
 * @author gjw
 *
 */

@Controller
@RequestMapping({ "/FinishedGoodService" })
public class FinishedGoodService {
	@Autowired
	HttpServletRequest request;

	private static final Logger log = LogR.getLogger(FinishedGoodService.class.getName());

	public static String softtype_finishgood = "cn.tianma.FinishedGood";// 成品软类型

	public static String typeOfString = "string";

	public static String typeOfFloat = "float";

	public static String typeOfTimeStamp = "timestamp";
	
	public static String typeOfInteger="integer";

	/**
	 * 查询成品属性 返回 需要成品的的IBA属性
	 * 
	 * @param number
	 * @param view
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmFinishedGoodAttSearch", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmFinishedGoodAttSearch(@RequestParam(value = "number", required = true) String number,
			@RequestParam(value = "view", required = false) String view, HttpServletResponse response)
			throws Exception {
		PrintWriter out = response.getWriter();
		response.setContentType("application/json; charset=UTF-8");
		String result = "";
		// 逻辑处理
		result = searhPart(number, view);
		out.print(result);
	}

	/**
	 * 查询成品属性 返回 需要成品的的IBA属性
	 * 
	 * @param number
	 * @param view
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmSearchFinishedGoodByAtt", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmSearchFinishedGoodByAtt(@RequestBody String param, HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		response.setContentType("application/json; charset=UTF-8");
		String result = "";
		// 逻辑处理
		try {
			param = URLDecoder.decode(param);
			System.out.println("==tmSearchFinishedGoodByAtt param:"+param);
			JSONObject obj = new JSONObject(param);
			result = getFinishGoodInfo(obj);
		} catch (Exception e) {
			log.info(e);
			result = TMECOUtil.errorRequestMessage();
		}
		out.print(result);
	}

	/**
	 * 查询成品属性
	 *
	 * @return
	 */
	public static String searhPart(String number, String view) {
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();
		// 找指定视图的BOM
		WTPart bompart = null;
		List<WTPart> partlist = new ArrayList<WTPart>();
		log.info("===========view:" + view);
		if (!isNullOrEmpty(view)) {
			log.info("===========view not null ==========");
			try {
				bompart = getPart(number, "", view);
				partlist.add(bompart);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} else {
			log.info("===========view  null ==========");
			partlist = getAllLatestVersionPart(number);
			log.info("===========view  partlist 2 ==========" + partlist.size());
		}

		for (WTPart part1 : partlist) {
			if (part1 != null) {
				try {
					JSONObject object = new JSONObject();
					Hashtable values = IBAUtil.getIBAValues(part1);
					Iterator iter = values.keySet().iterator();
					object.put("视图", part1.getViewName());
					while (iter.hasNext()) {
						String key = iter.next().toString();
						if (values.get(key) instanceof String) {
							String value = (String) values.get(key);
							String displayname = queryDisplayName(key, typeOfString);
							object.put(displayname, value);
						} else if (values.get(key) instanceof Timestamp) {
							Timestamp time = (Timestamp) values.get(key);
							String displayname = queryDisplayName(key, typeOfTimeStamp);
							object.put(displayname, time);
						} else if (values.get(key) instanceof Float) {
							float timevalue = (Float) values.get(key);
							String displayname = queryDisplayName(key, typeOfTimeStamp);
							object.put(displayname, timevalue);
						}

					}
					array.put(object);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		try {
			obj.put("datalist", array);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		log.info("====ext.tianma.bom.service.FinishedGoodService.searhPart:" + obj.toString());
		return obj.toString();
	}

	/**
	 * 空或者NULL值时返回true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str.equals("NULL"));
	}

	/**
	 * 根据部件编号获取所有最新小版本
	 * 
	 */
	public static List<WTPart> getAllLatestVersionPart(String number) {
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = getPart(part.getNumber(), v, part.getView().getName());
				if (null != p) {
					continue;
				}
				String version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
				log.info("view:" + part.getViewName() + "===version:" + version + "<br>");
				if (!list.contains(part)) {
					list.add(part);
				}
			}
		} catch (Exception e) {

		}
		return list;

	}

	/**
	 * 根据编号 版本 视图返回部件
	 * 
	 * @param num
	 * @param ver
	 * @param viewName
	 * @return
	 * @throws Exception
	 */
	public static WTPart getPart(String num, String ver, String viewName) throws Exception {
		if (viewName.equals(""))
			viewName = "Design";
		if (num == null || num.equals("") || num.trim().equals(""))
			return null;
		View view = ViewHelper.service.getView(viewName);
		WTPart part = null;
		QuerySpec qs = new QuerySpec(WTPart.class);
		SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, num);
		qs.appendWhere(sc);
		sc = new SearchCondition(WTPart.class, "view.key.id", SearchCondition.EQUAL,
				view.getPersistInfo().getObjectIdentifier().getId());
		qs.appendAnd();
		qs.appendWhere(sc);
		if (!ver.equals("")) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.versionida2versioninfo"),
					SearchCondition.EQUAL, new KeywordExpression("'" + ver + "'")));
		}
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
				new KeywordExpression("1")));

		qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			part = (WTPart) qr.nextElement();
			OneOffVersionInfo one = part.getOneOffVersionInfo();
			OneOffVersionIdentifier id = one.getIdentifier();
			String valueOneOff = id.getValue();
			if (valueOneOff == null)
				return part;
		}
		return part;
	}

	/**
	 * 根据IBA key查询IBA显示名称
	 * 
	 * @param key
	 * @return
	 */
	public static String queryDisplayName(String key, String type) {
		String displayname = "";
		log.info("========queryDisplayName  key====" + key);
		MethodContext context = MethodContext.getContext();
		WTConnection conn = null;
		boolean result = false;
		StringBuffer sb = new StringBuffer();
		if (typeOfString.equals(type)) {
			sb.append("select displayname from stringdefinition where name = ? ");
		} else if (typeOfTimeStamp.equals(type)) {
			sb.append("select displayname from timestampdefinition where name = ? ");
		} else if (typeOfFloat.equals(type)) {
			sb.append("select displayname from floatdefinition where name = ? ");
		} else if(typeOfInteger.equals(type)) {
			sb.append("select displayname from integerdefinition where name = ? ");
		}

		try {
			conn = (WTConnection) context.getConnection();
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			pstmt = conn.prepareStatement(sb.toString());
			pstmt.setString(1, key);
			log.info("========SQL====" + sb.toString());
			rs = pstmt.executeQuery();
			while (rs.next()) {
				displayname = rs.getString("displayname");
				result = true;
			}
			rs.close();
			rs = null;

			pstmt.close();
			pstmt = null;
			conn.release();
			conn = null;
		} catch (Exception e) {
			result = false;
		} finally {
			if (conn != null) {
				conn.release();
			}
		}
		return displayname;
	}

	/**
	 * 根据IBA属性获取成品信息数据
	 * 
	 * @param lang
	 * @return
	 */
	public static String getFinishGoodInfo(JSONObject keylist) throws WTException {
		JSONArray list = new JSONArray();
		URLFactory urlfactory;
		String baseHref = "";
		String url = "";
		try {
			urlfactory = new URLFactory();
			baseHref = urlfactory.getBaseHREF();
		} catch (WTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			log.info("====query start time==" + new Date());
		//	QueryResult qr = getWTPartByIBA2(softtype_finishgood, keylist);
			QuerySpec qs = new QuerySpec(WTPart.class);
			qs.setAdvancedQueryEnabled(true);
			// 类型过滤
			QueryUtil.appendTypeCondition(qs, softtype_finishgood);
			// 状态
			// qs.appendWhere(new
			// SearchCondition(WTPart.class,WTPart.LIFE_CYCLE_STATE,
			// SearchCondition.EQUAL,State.INWORK.toString()),new int[]{0});
			// IBA 属性过滤
			String condition = SearchCondition.EQUAL;
			Iterator<String> iter = keylist.keys();
			while (iter.hasNext()) {
				String key = iter.next();
				String value = "";
				if (keylist.get(key) != null) {
					value = keylist.get(key).toString();
					if(value.indexOf("*")!=-1){
						condition=SearchCondition.LIKE;
						value=value.replaceAll("\\*","%");
					}
					if(key.indexOf("finishedGoodDisplayMode")!=-1 && value.indexOf("*")==-1){
						//显示模式是枚举值， 查询条件不包含*   显示名称转为内部名称查询  
						String result = "";
						result = EnumerationUtil.getEnumerationDisplayValue2("显示模式", value);
						System.out.println("============result 1======"+result);
						if(!isNullOrEmpty(result)){
							value = result;
						}
						System.out.println("============value 1======"+value);

					}
					qs.appendAnd();
					// 属性 产品尺寸 是float类型
					if ("finishedGoodSize".equals(key)) {
						System.out.println("======getFinishGoodInfo float:" + key);
						qs.appendWhere(QueryUtil.getIBASearchConditionByFloat(WTPart.class, key, value, condition),
								new int[] { 0 });
					} else {
						System.out.println("======getFinishGoodInfo  string:" + key);
						// 其他为字符串类型
						qs.appendWhere(QueryUtil.getIBASearchCondition(WTPart.class, key, value, condition),
								new int[] { 0 });
					}
				}
			}
			// 最新版本
			System.out.println("=================getFinishGoodInfo qs==========" + qs.toString());
			QueryResult qr = PersistenceHelper.manager.find(qs);
			System.out.println("=================getFinishGoodInfo qr==========" + qr);

			qr = new LatestConfigSpec().process(qr);
			log.info("====query end time==" + new Date());
			System.out.println("======getFinishGoodInfo qr size:" + qr.size());
			while (qr.hasMoreElements()) {
				/*Object[] obj = (Object[]) qr.nextElement();
				WTPart part = (WTPart) obj[0];*/
				WTPart part = (WTPart)qr.nextElement();
				JSONObject hms = new JSONObject();

				String ufid;
				try {
					ufid = GenericUtil.getOid(part);
					url = baseHref + "app/#ptc1/tcomp/infoPage?oid="+ufid;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String href = "<a href=\""+url+"\" target=\"_blank\">"+part.getNumber()+"</a>";
				
				hms.put("name", part.getName());
				//hms.put("number", part.getNumber());
				hms.put("number", href);
				hms.put("url", url);

				Hashtable values = IBAUtil.getIBAValues(part);
				Iterator ibaiter = values.keySet().iterator();
				while (ibaiter.hasNext()) {
					String key = ibaiter.next().toString();
					if (values.get(key) instanceof String) {
						String value = (String) values.get(key);
						// String displayname = queryDisplayName(key);
						hms.put(key, value);
					} else if (values.get(key) instanceof Timestamp) {
						Timestamp time = (Timestamp) values.get(key);
						// String displayname = queryDisplayName(key);
						hms.put(key, time);
					} else if (values.get(key) instanceof Float) {
						Float value = (Float) values.get(key);
						// String displayname = queryDisplayName(key);
						hms.put(key, value);
					}

				}
				// finishedGoodResolution 分辨率
				// finishedGoodSize 产品尺寸
				// partMainSpecification 产品规格
				//
				list.put(hms);
				//System.out.println("..............result:" + part.getNumber());
			}

		} catch (Exception e) {
			// e.printStackTrace();
			log.error(e.getMessage(), e);
			System.out.println("====exception:" + e.getMessage());
		}
		return list.toString();
	}

	/**
	 * 通过参数获取对应部件
	 * 
	 * @param softtype
	 * @param viewName
	 * @param state
	 * @param ibaName
	 * @param iabValue
	 * @return
	 * @throws Exception
	 */
	public static List getWTPartByIBA(String softtype, JSONObject object)
			throws Exception {
		List<WTPart> list = new ArrayList<WTPart>();
		Iterator<String> iter = null;
		if (object != null) {
			iter = object.keys();
		}
		QuerySpec qs = new QuerySpec();
		int docIndex = qs.appendClassList(WTPart.class, true);
		int defIndex = qs.appendClassList(FloatDefinition.class, false);// StringDefinition
		int valueIndex = qs.appendClassList(FloatValue.class, false);
		int typeIndex = qs.appendClassList(WTTypeDefinition.class, false);
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida2a2"), SearchCondition.EQUAL,
				new KeywordExpression("A2.ida3a4")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A2.ida3a6"), SearchCondition.EQUAL,
				new KeywordExpression("A1.ida2a2")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.Ida2typedefinitionreference"),
				SearchCondition.EQUAL, new KeywordExpression("A3.ida2a2")));
		/*
		 * qs.appendAnd(); qs.appendWhere(new SearchCondition(new
		 * KeywordExpression("A1.name"), SearchCondition.EQUAL, new
		 * KeywordExpression("'"+ibaName+"'"))); qs.appendAnd();
		 * qs.appendWhere(new SearchCondition(new KeywordExpression("A2.value"),
		 * SearchCondition.EQUAL, new KeywordExpression("'"+iabValue+"'")));
		 */

		if (null != softtype) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + softtype + "'")));
		}
		if (iter != null) {
			while (iter.hasNext()) {
				String key = iter.next();
				String value = "";
				value = object.get(key).toString();
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A1.name"), SearchCondition.EQUAL,
						new KeywordExpression("'" + key + "'")));
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A2.value"), SearchCondition.EQUAL,
						new KeywordExpression("'" + value + "'")));

			}
		}

		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
				new KeywordExpression("1")));
		qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
		System.out.println("..........................qs:" + qs.toString());
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			Object[] obj = (Object[]) qr.nextElement();
			WTPart part = (WTPart) obj[0];
			list.add(part);
			System.out.println("..............result:" + part.getNumber());
		}
		return list;
	}
	/**
	 * 通过参数获取对应部件
	 * 
	 * @param softtype
	 * @param viewName
	 * @param state
	 * @param ibaName
	 * @param iabValue
	 * @return
	 * @throws Exception
	 */
	public static QueryResult getWTPartByIBA2(String softtype, JSONObject object)
			throws Exception {
		List<WTPart> list = new ArrayList<WTPart>();
		Iterator<String> iter = null;
		if (object != null) {
			iter = object.keys();
		}
		QuerySpec qs = new QuerySpec();
		int docIndex = qs.appendClassList(WTPart.class, true);
		int defIndex = qs.appendClassList(FloatDefinition.class, false);// StringDefinition
		int valueIndex = qs.appendClassList(FloatValue.class, false);
		int typeIndex = qs.appendClassList(WTTypeDefinition.class, false);
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.ida2a2"), SearchCondition.EQUAL,
				new KeywordExpression("A2.ida3a4")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A2.ida3a6"), SearchCondition.EQUAL,
				new KeywordExpression("A1.ida2a2")));
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.Ida2typedefinitionreference"),
				SearchCondition.EQUAL, new KeywordExpression("A3.ida2a2")));
		/*
		 * qs.appendAnd(); qs.appendWhere(new SearchCondition(new
		 * KeywordExpression("A1.name"), SearchCondition.EQUAL, new
		 * KeywordExpression("'"+ibaName+"'"))); qs.appendAnd();
		 * qs.appendWhere(new SearchCondition(new KeywordExpression("A2.value"),
		 * SearchCondition.EQUAL, new KeywordExpression("'"+iabValue+"'")));
		 */

		if (null != softtype) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A3.name"), SearchCondition.EQUAL,
					new KeywordExpression("'" + softtype + "'")));
		}
		if (iter != null) {
			while (iter.hasNext()) {
				String key = iter.next();
				String value = "";
				value = object.get(key).toString();
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A1.name"), SearchCondition.EQUAL,
						new KeywordExpression("'" + key + "'")));
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(new KeywordExpression("A2.value"), SearchCondition.EQUAL,
						new KeywordExpression("'" + value + "'")));

			}
		}

		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
				new KeywordExpression("1")));
		qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
		System.out.println("..........................qs:" + qs.toString());
		QueryResult qr = PersistenceHelper.manager.find(qs);
		/*while (qr.hasMoreElements()) {
			Object[] obj = (Object[]) qr.nextElement();
			WTPart part = (WTPart) obj[0];
			list.add(part);
			System.out.println("..............result:" + part.getNumber());
		}*/
		return qr;
	}

}
